package com.sg.common;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sg.controller.UserController;
import com.sg.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

@Component   //在容器中进行注册
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader(UserController.AUTH_HEADER_NAME);
        if(!StringUtils.hasLength(token) || !JWTUtil.verify(token, UserController.TOEKN_KEY.getBytes())){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseInfo.error(CodeMsg.AUTH_ERROR)));
            return false;
        }
        // 校验redis数据
        JWT jwt = JWTUtil.parseToken(token);
        Object uid = jwt.getPayload().getClaim("uid");
        String s = stringRedisTemplate.opsForValue().get(UserController.TOEKN_KEY_REDIS_TOKEN + token);
        if(!StringUtils.hasLength(s)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseInfo.error(CodeMsg.AUTH_ERROR)));
            return false;
        }
        UserInfo userInfo = JSON.parseObject(s, UserInfo.class);
        Integer id = userInfo.getId();
        String string = uid.toString();

        if(Integer.parseInt(string) == id){
            stringRedisTemplate.opsForValue().set(UserController.TOEKN_KEY_REDIS_TOKEN+token, JSON.toJSONString(userInfo),78, TimeUnit.HOURS);
            return true;
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(ResponseInfo.error(CodeMsg.AUTH_ERROR)));
        return false;
    }
}
